package com.azarias.controller;


import com.azarias.model.pojo.Registry;
import com.azarias.model.pojo.ServiceInstance;
import com.azarias.model.vo.HeartbeatRequest;
import com.azarias.model.vo.HeartbeatResponse;
import com.azarias.model.vo.RegisterRequest;
import com.azarias.model.vo.RegisterResponse;
import lombok.extern.slf4j.Slf4j;

/**
 * @description: client端调用的服务入口
 * @author: Azarias_Jx
 * @date: 2022/1/2 14:11
 */
@Slf4j
public class RegisterServerController {
    //注册表
    private Registry registry = Registry.getInstance();

    /**
     * 服务注册
     * @param registerRequest
     * @return
     */
    public RegisterResponse register(RegisterRequest registerRequest) {
        RegisterResponse registerResponse = new RegisterResponse();
        try {
            ServiceInstance serviceInstance = new ServiceInstance();
            serviceInstance.setServiceName(registerRequest.getServiceName());
            serviceInstance.setIp(registerRequest.getIp());
            serviceInstance.setHostName(registerRequest.getHostname());
            serviceInstance.setPort(registerRequest.getPort());

            registry.register(serviceInstance);
            registerResponse.setStatus(RegisterResponse.SUCCESS);
            registerResponse.setServiceInstanceId(serviceInstance.getServiceInstanceId());
        } catch (Exception e) {
            e.printStackTrace();
            registerResponse.setStatus(RegisterResponse.FAILURE);
        }
        return registerResponse;
    }

    /**
     *心跳，包含续约功能
     * @return
     */
    public HeartbeatResponse heartbeat(HeartbeatRequest heartbeatRequest){
        HeartbeatResponse heartbeatResponse = new HeartbeatResponse();
        try {
            ServiceInstance serviceInstance = registry.getServiceInstance(heartbeatRequest.getServiceName(), heartbeatRequest.getServiceInstanceId());
            serviceInstance.renew();
            heartbeatResponse.setStatus(HeartbeatResponse.SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            heartbeatResponse.setStatus(HeartbeatResponse.FAILURE);
        }

        return heartbeatResponse;
    }
}
